/* eslint-disable no-multiple-empty-lines */
<template>
  <div class="rule">
    <SearchBar @onSearch="handleSearch" @childFn="resetFormSearch">
      <SearchBarItem label="商户名称：" :labelLg="8">
        <Input type="text" v-model="searchModule.merchantName" placeholder="请输入商户名称" clearable/>
      </SearchBarItem>
      <SearchBarItem label="产品名称：" :labelLg="8">
        <Input type="text" v-model="searchModule.productName" placeholder="请输入产品名称" clearable/>
      </SearchBarItem>
      <SearchBarItem label="规则名称：" :labelLg="8">
        <Input type="text" v-model="searchModule.ruleName" placeholder="请输入规则名称" clearable/>
      </SearchBarItem>
      <SearchBarItem label="规则编码：" :labelLg="8">
        <Input type="text" v-model="searchModule.ruleCode" placeholder="请输入规则编码" clearable/>
      </SearchBarItem>
      <SearchBarItem label="规则有效时间：" :labelLg="8">
        <DatePicker type="daterange" class="searchDate" ref="createDatePicker" :value="searchModule.dataTime"
                    split-panels placeholder="请选择" @on-change="searchTime"></DatePicker>
      </SearchBarItem>
      <SearchBarItem label="结算类型：" :labelLg="8">
        <Select v-model="searchModule.settlementType" placeholder="请选择" :clearable="isClear">
          <Option :value="item.key" v-for="(item, key) in seleteSettlementType" :key="key">{{ item.value }}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="清分规则：" :labelLg="8">
        <Select v-model="searchModule.clearingRule" placeholder="请选择" :clearable="isClear">
          <Option :value="item.key" v-for="(item, key) in seleteSettlementRule" :key="key">{{ item.value }}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="规则类型：" :labelLg="8">
        <Select v-model="searchModule.ruleType" placeholder="请选择" :clearable="isClear">
          <Option :value="item.key" v-for="(item, key) in seleteRuleType" :key="key">{{ item.value }}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="规则状态：" :labelLg="8">
        <Select v-model="searchModule.settlementStatus" placeholder="请选择" :clearable="isClear">
          <Option :value="item.key" v-for="(item, key) in seleteSettlementStatus" :key="key">{{ item.value }}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="商户编码：" :labelLg="8">
        <Input type="text" v-model="searchModule.merchantCode" placeholder="请输入商户编码" clearable/>
      </SearchBarItem>
      <SearchBarItem label="商品编码：" :labelLg="8">
        <Input type="text" v-model="searchModule.productCode" placeholder="请输入商品编码" clearable/>
      </SearchBarItem>
    </SearchBar>
    <RemoteTable :namespace="namespace" :columns="columns" @onSortChange="onSortChange">
      <template #extra>
        <Authc permissions="trade:merchant:rule:edit">
          <Button type="primary" @click="handleAdd">新增</Button>
        </Authc>
        <Authc permissions="trade:merchant:rule:export">
          <Button type="primary" @click="exportExcel">导出</Button>
        </Authc>
      </template>
    </RemoteTable>

    <!-- 编辑弹窗 -->
    <Modal v-model="isShow" :visible.sync="isShow" :title="title" width='800' class="ruleModal">
      <Loading :loading="false">
        <Form ref="dataModule" :label-width="130" :model="dataModule" :rules="ruleValidate">

          <FormItem label="规则类型：" prop="ruleType">
            <RadioGroup v-model="dataModule.ruleType" @on-change="handleTypeGadio">
              <Radio v-for="item in seleteRuleType" :key="item.value" :label="item.key">{{ item.value }}</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem label="所属商户：" prop="merchantCode">
            <Select v-model="dataModule.merchantCode" :label-in-value="true" filterable placeholder="请选择"
                    @on-change="bindleMCode">
              <Option v-for="item in merchantNameSelect" :key="item.value" :value="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>

          <FormItem label="所属产品：" prop="productCode" v-if="dataModule.merchantCode">
            <Select v-model="dataModule.productCode" :label-in-value="true" filterable placeholder="请选择"
                    @on-change="bindleProductCode">
              <Option v-for="(item, index) in productNameSelect" :key="index" :value="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>

          <FormItem label="产品编码：" v-if="dataModule.productCode">
            <div>{{ dataModule.productCode }}</div>
          </FormItem>

          <FormItem prop="ruleName" label="规则名称：">
            <Input type="text" v-model="dataModule.ruleName" placeholder="请填写,字数不超过32" maxlength="32"/>
          </FormItem>

          <FormItem label="结算类型：" prop="settlementType">
            <Select v-model="dataModule.settlementType" placeholder="请选择" @on-change="handleCloseType">
              <Option v-for="(item, index) in seleteSettlementType" :key="item + index" :value="item.key">{{
                  item.value
                }}
              </Option>
            </Select>
          </FormItem>

          <FormItem label="产品单价：" prop="productPrice" v-if="dataModule.ruleType == '1'">
            <Input type="text" v-model="dataModule.productPrice" placeholder="请填写">
              <span slot="append">元</span>
            </Input>
          </FormItem>

          <Row>
            <Col span="11">
              <FormItem label="清分周期类型：" prop="clearingCycleMode">
                <Radio-group v-model="dataModule.clearingCycleMode">
                  <Radio label="1">天</Radio>
                  <Radio label="2">月</Radio>
                </Radio-group>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="清分日期：" v-if="dataModule.clearingCycleMode == '1'">
                <span v-if="dataModule.clearingCycleValue">T + {{ dataModule.clearingCycleValue }}</span>
              </FormItem>
              <FormItem label="清分日期：" v-if="dataModule.clearingCycleMode == '2'">
                <span>{{ dataModule.clearingCycleValueExt }}日 / {{ dataModule.clearingCycleValue }}个月 </span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="11">
              <FormItem prop="clearingCycleValue" label="清分周期值：">
                <Input type="text" v-model="dataModule.clearingCycleValue" placeholder="请填写月份"/>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem prop="clearingCycleValueExt" label="清分周期拓展值：" v-if="dataModule.clearingCycleMode == '2'">
                <Input type="text" v-model="dataModule.clearingCycleValueExt" placeholder="请填写日期"/>
              </FormItem>
            </Col>
          </Row>

          <!-- 产品 && 结算类型为 清分 -->
          <div v-if="typeRadioDataType && dataModule.settlementType == '1'">
            <FormItem label="清分规则：" prop="clearingRule" :rules="{ required: closeTypeDataType, validator: validateSequence }">
              <Radio-group v-model="dataModule.clearingRule">
                <Radio v-for="item in seleteSettlementRule" :key="item.value" :label="item.key">{{ item.value }}&#160;&#160;</Radio>
              </Radio-group>
            </FormItem>

            <Row v-if="dataModule.clearingRule == '1'">
              <Col span="12">
                <FormItem label="平台应收：" prop="platformReceivable" :rules="{ required: closeTypeDataType, validator: validateTage, trigger: 'blur' }">
                  <Input type="text" v-model="dataModule.platformReceivable" placeholder="请填写" @on-change="changePlatform">
                    <span slot="append">%</span>
                  </Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收：" prop="merchantReceivable" :rules="{ required: closeTypeDataType, validator: validateTage, trigger: 'blur' }">
                  <Input type="text" v-model="dataModule.merchantReceivable" placeholder="请填写" @on-change="changeMerchant">
                    <span slot="append">%</span>
                  </Input>
                </FormItem>
              </Col>
            </Row>

            <Row v-if="dataModule.clearingRule == '2'">
              <Col span="12">
                <FormItem label="平台应收：" prop="platformReceivable" :rules="{ required: closeTypeDataType, validator: closeTypeDataTypePrice, trigger: 'blur' }">
                  <Input type="text" v-model="dataModule.platformReceivable" placeholder="请填写" @on-change="changePricePlatform">
                    <span slot="append">元</span>
                  </Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收：" prop="merchantReceivable"
                          :rules="{ required: closeTypeDataType, validator: closeTypeDataTypePrice, trigger: 'blur' }">
                  <span>{{ dataModule.merchantReceivable }}&#160;&#160;&#160;&#160;元</span>
                </FormItem>
              </Col>
            </Row>

            <Row v-if="dataModule.clearingRule == '3'">
              <Col span="12">
                <FormItem label="平台应收：" prop="platformReceivable"
                          :rules="{ required: closeTypeDataType, validator: closeTypeDataTypePrice, trigger: 'blur' }">
                  <span>{{ dataModule.platformReceivable }}&#160;&#160;&#160;&#160;元</span>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收：" prop="merchantReceivable"
                          :rules="{ required: closeTypeDataType, validator: closeTypeDataTypePrice, trigger: 'blur' }">
                  <Input type="text" v-model="dataModule.merchantReceivable" placeholder="请填写"
                         @on-change="changePriceMerchant">
                    <span slot="append">元</span>
                  </Input>
                </FormItem>
              </Col>
            </Row>
          </div>

          <!-- 通用 && 结算类型为 清分 -->
          <div v-if="!typeRadioDataType && dataModule.settlementType === '1'">
            <FormItem label="清分规则">
              <div>百分比</div>
            </FormItem>

            <Row>
              <Col span="12">
                <FormItem label="平台应收：" prop="platformReceivable"
                          :rules="{ required: closeTypeDataType, validator: validateTage, trigger: 'blur' }">
                  <Input type="text" v-model="dataModule.platformReceivable" placeholder="请填写"
                         @on-change="changePlatform">
                    <span slot="append">%</span>
                  </Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收：" prop="merchantReceivable"
                          :rules="{ required: closeTypeDataType, validator: validateTage, trigger: 'blur' }">
                  <Input type="text" v-model="dataModule.merchantReceivable" placeholder="请填写"
                         @on-change="changeMerchant">
                    <span slot="append">%</span>
                  </Input>
                </FormItem>
              </Col>
            </Row>
          </div>

          <!-- (产品 || 通用) && 结算类型为 自营 -->
          <div v-if="dataModule.settlementType === '2'">
            <FormItem label="清分规则：">
              <div>百分比</div>
            </FormItem>

            <Row>
              <Col span="12">
                <FormItem label="平台应收：">
                  <div>100%</div>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收：">
                  <div>0%</div>
                </FormItem>
              </Col>
            </Row>
          </div>

          <!-- (产品 || 通用) && 结算类型为 平台 -->
          <div v-if="dataModule.settlementType === '3'">
            <FormItem label="清分规则：">
              <div>百分比</div>
            </FormItem>

            <Row>
              <Col span="12">
                <FormItem label="平台应收：">
                  <div>100%</div>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收：">
                  <div>0%</div>
                </FormItem>
              </Col>
            </Row>

            <div class="offlineSettleRule">
              <FormItem label="线下结算规则：" prop="lineClearingRule">
                <Radio-group v-model="dataModule.lineClearingRule">
                  <Radio v-for="item in seleteSettlementRule" :key="item.value" :label="item.key">{{ item.value }}
                  </Radio>
                </Radio-group>
              </FormItem>

              <Row v-if="dataModule.lineClearingRule == '1'">
                <Col span="12">
                  <FormItem label="平台应收：" prop="linePlatformReceivable"
                            :rules="{ required: lineCloseTypeDataType, validator: validateTageLine, trigger: 'blur' }">
                    <Input type="text" v-model="dataModule.linePlatformReceivable" placeholder="请填写"
                           @on-change="changeLinePlatform">
                      <span slot="append">%</span>
                    </Input>
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="商户应收：" prop="lineMerchantReceivable"
                            :rules="{ required: lineCloseTypeDataType, validator: validateTageCheakLine, trigger: 'blur' }">
                    <Input type="text" v-model="dataModule.lineMerchantReceivable" placeholder="请填写"
                           @on-change="changeLineMerchant">
                      <span slot="append">%</span>
                    </Input>
                  </FormItem>
                </Col>
              </Row>

              <Row v-if="dataModule.lineClearingRule == '2'">
                <Col span="12">
                  <FormItem label="平台应收：" prop="linePlatformReceivable"
                            :rules="{ required: lineCloseTypeDataType, validator: validateSequence, trigger: 'blur' }">
                    <Input type="text" v-model="dataModule.linePlatformReceivable" placeholder="请填写">
                      <span slot="append">元</span>
                    </Input>
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="商户应收：" prop="lineMerchantReceivable"
                            :rules="{ required: lineCloseTypeDataType, validator: validateSequence, trigger: 'blur' }">
                    <Input type="text" v-model="dataModule.lineMerchantReceivable" placeholder="请填写">
                      <span slot="append">元</span>
                    </Input>
                  </FormItem>
                </Col>
              </Row>
            </div>
          </div>

          <FormItem label="有效时间：" prop="validTime">
            <DatePicker v-model="dataModule.validTime" format="yyyy-MM-dd" type="daterange" placeholder="请选择"
                        @on-change="setDateRange" @on-clear="handleClear" clearable></DatePicker>
          </FormItem>

          <FormItem label="优先级：" prop="priorityLevel">
            <Input type="text" v-model.trim="dataModule.priorityLevel" placeholder="请填写"/>
          </FormItem>
        </Form>
      </Loading>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitCancel('dataModule')">取消</Button>
        <Button type="primary" @click="handleSubmit('dataModule')">确定</Button>
      </div>
    </Modal>

    <!-- 详情弹窗 -->
    <Modal v-model="isShowDetele" :visible.sync="isShowDetele" :title="dataModuleDetele.ruleName" width='800'
           class="ruleDeteleModal" :footer-hide="true">
      <Loading :loading="false">
        <Form ref="dataModuleDetele" :label-width="130" :model="dataModuleDetele">

          <div class="controlNo">规则编号：{{ dataModuleDetele.ruleCode }}</div>

          <h3 class="ruleDeteleTitle">产品信息</h3>

          <FormItem label="所属商户：">
            <span>{{ dataModuleDetele.merchantName }}</span>
          </FormItem>

          <FormItem label="商户编码：">
            <span>{{ dataModuleDetele.merchantCode }}</span>
          </FormItem>

          <FormItem label="所属产品：">
            <span>{{ dataModuleDetele.productName }}</span>
          </FormItem>

          <FormItem label="产品编码：">
            <span>{{ dataModuleDetele.productCode }}</span>
          </FormItem>

          <h3 class="ruleDeteleTitle">规则信息</h3>

          <FormItem label="规则名称：">
            <span>{{ dataModuleDetele.ruleName }}</span>
          </FormItem>

          <Row>
            <Col span="11">
              <FormItem label="规则类型：">
                <span>{{ dataModuleDetele.ruleTypeCn }}</span>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="结算类型：">
                <span>{{ dataModuleDetele.settlementTypeCn }}</span>
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="11">
              <FormItem label="产品单价：" v-if="dataModuleDetele.ruleType === '1'">
                <span>{{ dataModuleDetele.productPrice ? `${dataModuleDetele.productPrice}元` : '' }}</span>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="清分规则：">
                <span>{{ dataModuleDetele.clearingRuleCn }}</span>
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="11">
              <FormItem label="平台应收：">
                <span>{{
                    dataModuleDetele.clearingRule == '1' ? `${dataModuleDetele.platformReceivable}%` : `${dataModuleDetele.platformReceivable}元`
                  }}</span>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="商户应收：">
                <span>{{
                    dataModuleDetele.clearingRule == '1' ? `${dataModuleDetele.merchantReceivable}%` : `${dataModuleDetele.merchantReceivable}元`
                  }}</span>
              </FormItem>
            </Col>
          </Row>

          <FormItem label="清分日期：">
            <span
                v-if="dataModuleDetele.clearingCycleMode == 1">T + {{ dataModuleDetele.clearingCycleValue }}</span>
            <span v-else>{{ dataModuleDetele.clearingCycleValueExt }}日/ {{
                dataModuleDetele.clearingCycleValue
              }}个月</span>
          </FormItem>

          <Row>
            <Col span="11">
              <FormItem label="清分周期值：">
                <span>{{ dataModuleDetele.clearingCycleValue }}</span>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="清分周期拓展值：" v-if="dataModuleDetele.clearingCycleMode != 1">
                <span>{{ dataModuleDetele.clearingCycleValueExt }}</span>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="清分周期类型：">
                <span>{{ dataModuleDetele.clearingCycleMode == 1 ? '按天' : '按月' }}</span>
              </FormItem>
            </Col>
          </Row>

          <FormItem label="有效时间：">
            <span>{{ dataModuleDetele.effectiveDate }} ~ {{ dataModuleDetele.expireDate }}</span>
          </FormItem>

          <FormItem label="优先级：">
            <span>{{ dataModuleDetele.priorityLevel }}</span>
          </FormItem>
        </Form>
      </Loading>
    </Modal>
  </div>
</template>

<script>
import {
  Button,
  Input,
  InputNumber,
  Modal,
  Message,
  Col,
  Row,
  Form,
  FormItem,
  DatePicker,
  Select,
  Option,
  Card,
  Radio,
  RadioGroup
} from "view-design";
import Loading from "@/components/Loading";
import RemoteTable from "@/components/RemoteTable";
import RemoteSelect from "@/components/RemoteSelect";
import SearchBar from "@/components/SearchBar";
import {namespace} from "../module/rule";
import Authc from "@/components/Authc";
import Action from "./Action";
import config from "@/utils/config";
import appService from "@/utils/appService";
import utils from '@/utils/util';

export default {
  name: "tables_page",
  components: {
    Loading,
    RemoteTable,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    RemoteSelect,
    Authc,
    Action,
    Button,
    Input,
    InputNumber,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card,
    Radio,
    RadioGroup
  },
  inject: ['reload'], // 重新涮新页面
  data() {
    return {
      title: "",
      isShow: false,
      isShowDetele: false,
      namespace: namespace,
      loading: true,
      isClear: true,
      dataModule: {
        ruleType: '1',
        effectiveDate: '',
        expireDate: ''
      },
      dataModuleDetele: {},
      searchModule: {
        // effectiveDate: '',
        // expireDate: ''
      },
      ruleValidate: {
        ruleType: [{required: true, message: '请选择', trigger: 'change'}],
        merchantCode: [{required: true, message: '请选择', trigger: 'change'}],
        productCode: [{required: true, message: '请选择', trigger: 'change'}],
        ruleName: [{required: true, message: '请填写', trigger: 'blur'}],
        productPrice: [{required: true, validator: this.validateSequence, trigger: "blur"}],
        settlementType: [{required: true, message: '请选择', trigger: 'change'}],
        clearingCycleMode: [{required: true, message: '请选择', trigger: 'change'}],
        clearingCycleValue: [{required: true, validator: utils.validateMonth, trigger: "blur"}],
        clearingCycleValueExt: [{required: true, validator: utils.validateDay, trigger: "blur"}],

        validTime: [{required: true, validator: this.validateDaterange, trigger: "change"}],
        priorityLevel: [{required: true, validator: this.validatelevel, trigger: "blur"}]
      },
      productNameSelect: [], // 产品
      productBusinessCodeMap: new Map(), // 业务侧商品编码
      merchantNameSelect: [], // 商户
      columns: [
        {
          title: "序号",
          type: "index",
          width: 80,
          align: "center"
          // fixed: "left"
        },
        {
          title: "规则编码",
          key: "ruleCode",
          minWidth: 270,
          align: "center"
          // fixed: "left"
        },
        {
          title: "优先级",
          key: "priorityLevel",
          minWidth: 100,
          align: "center"
        },
        {
          title: "商户名称",
          key: "merchantName",
          minWidth: 200,
          align: "center"
        },
        {
          title: "产品名称",
          key: "productName",
          minWidth: 200,
          align: "center"
        },
        {
          title: "产品编码",
          key: "productCode",
          minWidth: 100,
          align: "center"
        },
        {
          title: "规则类型",
          key: "ruleTypeCn",
          minWidth: 150,
          align: "center"
        },
        {
          title: "规则名称",
          key: "ruleName",
          minWidth: 150,
          align: "center"
        },
        {
          title: "结算类型",
          key: "settlementTypeCn",
          minWidth: 150,
          align: "center"
        },
        {
          title: "清分规则",
          key: "clearingRuleCn",
          minWidth: 150,
          align: "center"
        },
        {
          title: "状态",
          key: "settlementStatusCn",
          minWidth: 150,
          align: "center"
        },
        {
          title: "规则生效时间",
          key: "effectiveDate",
          minWidth: 150,
          align: "center"
        },
        {
          title: "规则失效时间",
          key: "expireDate",
          minWidth: 150,
          align: "center"
        },
        {
          title: "操作",
          key: "action",
          width: 150,
          // fixed: "right",
          align: "center",
          permissions: ["trade:merchant:rule"],
          render: function (h, data) {
            return h(Action, {
              props: {
                row: data.row
              }
            });
          }
        }
      ],
      seleteSettlementType: [], // 结算类型
      seleteSettlementRule: [], // 清分规则
      seleteRuleType: [], // 规则类型
      seleteSettlementStatus: [], //规则状态
      typeRadioDataType: true,  // 自定义规则状态
      closeTypeDataType: true, // 平台、商户应收 是否需要验证
      lineCloseTypeDataType: true // 线下平台、商户应收 是否需要验证
    };
  },
  created() {
    /** 如果 url 没有带参数，就重置请求参数 **/
    this.$store.commit(`${namespace}/reviseQuery`);
    this.getMerchantSearchKey();
  },
  watch: {
    'dataModule.clearingRule'(newvalue, oldValue) {
      if (newvalue) {
        this.$set(this.dataModule, 'platformReceivable', '');
        this.$set(this.dataModule, 'merchantReceivable', '');
      }
    },
    'dataModule.lineClearingRule'(newVlue, oldValue) {
      if (newVlue) {
        this.$set(this.dataModule, 'linePlatformReceivable', '');
        this.$set(this.dataModule, 'lineMerchantReceivable', '');
        this.resetLineReceivable();
      }
    }
  },
  methods: {
    /** 验证价格数字 **/
    validateSequence(rule, value, callback) {
      let reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
      if (value === '' || !Number(value)) {
        callback(new Error('最大值允许输入10位数，且保留2位小数'));
      } else if (!reg.test(value + '')) {
        callback(new Error('最大值允许输入10位数，且保留2位小数'));
      } else if ((value + '').length > 10) {
        callback(new Error('最大值允许输入10位数，且保留2位小数'));
      } else {
        callback();
      }
    },

    /** 验证 平台-商户金额 = 价格数字 **/
    closeTypeDataTypePrice(rule, value, callback) {
      let reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
      if (value === '' || !Number(value)) {
        callback(new Error('最大值允许输入10位数，且保留2位小数1'));
      } else if (!reg.test(value + '')) {
        callback(new Error('最大值允许输入10位数，且保留2位小数2'));
      } else if (value > this.dataModule.productPrice && value < 0) {
        callback(new Error('平台、商户应收之和不能超过产品单价3'));
      }
      callback();
    },

    /** 整整数验证 **/
    validatelevel(rule, value, callback) {
      let tag = /^\d+$/;
      if (value === '' || !Number(value)) {
        callback(new Error('请正确填写优先级'));
      } else if (!tag.test(value)) {
        callback(new Error('请正确填写优先级'));
      } else if (value > 10000) {
        callback(new Error('请正确填写优先级'));
      } else {
        callback();
      }
    },

    /** 表单 日期验证 **/
    validateDaterange(rule, value, callback) {
      if (!value) {
        callback(new Error("日期不能为空"))
      } else {
        callback();
      }
    },

    /** 百分比验证 */
    validateTage(rule, value, callback) {
      let reg = /^(([0-9]{1}\d*)|(0{1}))(\.\d{0,2})?$/
      if (value === '') {
        callback(new Error('请输入数字'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字且保留两位小数'));
      } else if (value > 100) {
        callback(new Error('平台、商户应收之和不能超过100%'));
      } else if (value.split('.')[1] === '') {
        callback(new Error('请填写正确百分比'))
      }
      callback();
    },
    /** 线下百分比验证 */
    validateTageLine(rule, value, callback) {
      let reg = /^(([0-9]{1}\d*)|(0{1}))(\.\d{0,2})?$/
      if (value === '') {
        callback(new Error('请输入数字'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字且保留两位小数'));
      } else if (value > 100) {
        callback(new Error('平台、商户应收之和不能超过100%'));
      } else if (value.split('.')[1] === '') {
        callback(new Error('请填写正确百分比'))
      }
      callback();
    },

    /** 百分比验证 */
    validateTageCheak(rule, value, callback) {
      let reg = /^(([0-9]{1}\d*)|(0{1}))(\.\d{0,2})?$/
      if (value === '') {
        callback(new Error('请输入数字'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字且保留两位小数'));
      } else if (value > 100) {
        callback(new Error('平台、商户应收之和不能超过100%'));
      } else if ((value).split('.')[1] === '') {
        callback(new Error('请填写正确百分比1'))
      }
      callback();
    },
    /** 线下百分比验证 */
    validateTageCheakLine(rule, value, callback) {
      let reg = /^(([0-9]{1}\d*)|(0{1}))(\.\d{0,2})?$/
      if (!value) {
        callback(new Error('请输入数字'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字且保留两位小数'));
      } else if (value > 100) {
        callback(new Error('平台、商户应收之和不能超过100%'));
      } else if ((value + '').split('.')[1] === '') {
        callback(new Error('请填写正确百分比'))
      }
      callback();
    },
    /** 导出 */
    async exportExcel() {
      try {
        let res = await this.$store.dispatch(`${namespace}/exportExcel`, this.searchModule);

        utils.exportExcle(res, '清分规则表');
      } catch (error) {
        this.$Message.error({
          content: '导出失败'
        })
      }
    },

    /** 平台 - 商户 金额 = 产品单价 */
    changePricePlatform() {
      this.$set(this.dataModule, 'merchantReceivable', (this.dataModule.productPrice - this.dataModule.platformReceivable).toFixed(2) + '')
    },

    changePriceMerchant() {
      this.$set(this.dataModule, 'platformReceivable', (this.dataModule.productPrice - this.dataModule.merchantReceivable).toFixed(2) + '')
    },

    /** 平台百分比 - 商户百分比 = 100 */
    changePlatform() {
      this.$set(this.dataModule, 'merchantReceivable', (100 - this.dataModule.platformReceivable) + '');
      if (this.dataModule.platformReceivable.indexOf('.') > -1) {
        this.$set(this.dataModule, 'merchantReceivable', (100 - this.dataModule.platformReceivable).toFixed(2));
      }
    },

    changeMerchant() {
      this.$set(this.dataModule, 'platformReceivable', (100 - this.dataModule.merchantReceivable) + '');
      if (this.dataModule.merchantReceivable.indexOf('.') > -1) {
        this.$set(this.dataModule, 'platformReceivable', (100 - this.dataModule.merchantReceivable).toFixed(2));
      }
    },

    /** 线下平台百分比 - 商户百分比 = 100 */
    changeLinePlatform() {
      this.dataModule.lineMerchantReceivable = 100 - this.dataModule.linePlatformReceivable;
      if (this.dataModule.linePlatformReceivable.indexOf('.') > -1) {
        this.dataModule.lineMerchantReceivable = (100 - this.dataModule.linePlatformReceivable).toFixed(2);
      }
    },

    changeLineMerchant() {
      this.dataModule.linePlatformReceivable = 100 - this.dataModule.lineMerchantReceivable;
      if (this.dataModule.lineMerchantReceivable.indexOf('.' > -1)) {
        this.dataModule.linePlatformReceivable = (100 - this.dataModule.lineMerchantReceivable).toFixed(2);
      }
    },

    // 清空事件；
    resetFormSearch() {
      this.$set(this.searchModule, 'merchantName', '');  //商户名称
      this.$set(this.searchModule, 'productName', '');   //产品名称
      this.$set(this.searchModule, 'ruleName', '');      //规则名称
      this.$set(this.searchModule, 'ruleCode', '');      //规则编码
      this.$set(this.searchModule, 'settlementType', '');  //结算类型
      this.$set(this.searchModule, 'clearingRule', '');  //清分规则
      this.$set(this.searchModule, 'ruleType', '');  //规则类型
      this.$set(this.searchModule, 'settlementStatus', ''); //规则状态
      this.$set(this.searchModule, 'merchantCode', ''); //商户编码
      this.$set(this.searchModule, 'productCode', ''); //商品编码
      // 清空时间选择
      this.$refs["createDatePicker"].handleClear();
    },

    // 商户
    async getMerchant() {
      try {
        let page = {
          currentPage: 1,
          pageSize: 9999
        }
        let res = await this.$store.dispatch(`${namespace}/getMerchant`, page);
        if (res.data.ret === 0) {
          let data = res.data.data.list.map(({merchantName, merchantCode}) => {
            return {
              label: merchantName ? merchantName : '',
              value: merchantCode ? merchantCode : ''
            }
          })
          this.merchantNameSelect = data;
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },

    // 商品 & 产品
    async getProductList(data) {
      try {
        let page = {
          currentPage: 1,
          pageSize: 9999,
          merchantCode: data ? data.value : ''
        }
        let res = await this.$store.dispatch(`${namespace}/getProduct`, page);
        if (res.data.ret === 0) {
            let productNameSelects=[]
          res.data.data.list.forEach(d => {
              productNameSelects.push({
              label: d.productName ? d.productName : '',
              value: d.productCode ? d.productCode : '',
               businessCode: d.productCodeBusiness ? d.productCodeBusiness : '----'
            });
            this.productBusinessCodeMap.set(d.productCode, d.productCodeBusiness);
          })

            this.productNameSelect=productNameSelects;
            let dataModule= this.dataModule
            dataModule.productCode=null;
            dataModule.productCodeBusiness=null;
            dataModule.productName='';
            this.dataModule=dataModule
          /*let data = res.data.data.list.map(({ productName, productCode, productCodeBusiness }) => {
            return {
              label: productName ? productName : '',
              value: productCode ? productCode : '',
              businessCode: productCodeBusiness ? productCodeBusiness : '----'
            }
          })
          this.productNameSelect = data;*/
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },

    // 字典
    async getMerchantSearchKey() {
      try {
        let res = await this.$store.dispatch(`${namespace}/getMerchantSearchKey`);
        if (res.data.ret === 0) {
          let data = res.data.data;
          this.seleteRuleType = data.settlementCycleMode; // 规则类型
          this.seleteSettlementType = data.settlementType; // 结算类型
          this.seleteSettlementRule = data.settlementClearRule; // 清分规则
          this.seleteSettlementStatus = data.settlementStatus; // 状态
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },
    // 所属产品
    bindleProductCode(val) {
      this.dataModule.productName = val ? val.label : '';
      this.dataModule.productCodeBusiness = this.productBusinessCodeMap.get(val.value);
    },

    // 所属商户
    bindleMCode(val) {
      this.dataModule.merchantName = val ? val.label : '';
      if (val) this.getProductList(val);
    },

    // 编辑有效时间
    setDateRange(val) {
      this.dataModule.validTime = val
      this.dataModule.effectiveDate = val[0]
      this.dataModule.expireDate = val[1]
    },
    handleClear() {
      this.$set(this.dataModule, 'validTime', [])
    },

    // 搜索时间
    searchTime(date, type) {
      this.searchModule.effectiveDate = date ? date[0] : ''
      this.searchModule.expireDate = date ? date[1] : ''
    },

    // 结算类型
    handleCloseType(val) {
      this.$set(this.dataModule, 'settlementType', val + '');
      if (this.typeRadioDataType) {
        // 产品规则
        if (val == '1') {
          /** 清分 */
          this.closeTypeDataType = true;
          this.lineCloseTypeDataType = false;
          this.resetLineReceivable();
          this.$set(this.dataModule, 'lineClearingRule', '');
          this.$set(this.dataModule, 'platformReceivable', '');
          this.$set(this.dataModule, 'merchantReceivable', '');
        } else if (val == '2') {
          /** 结算 */
          this.closeTypeDataType = false;
          this.lineCloseTypeDataType = false;
          this.resetReceivable();
          this.resetLineReceivable();
          this.$set(this.dataModule, 'lineClearingRule', '');
          this.$set(this.dataModule, 'platformReceivable', '100');
          this.$set(this.dataModule, 'merchantReceivable', '0');
        } else if (val == '3') {
          /** 平台 */
          this.closeTypeDataType = false;
          this.lineCloseTypeDataType = true;
          this.resetReceivable();
          this.$set(this.dataModule, 'lineClearingRule', '1');
          this.$set(this.dataModule, 'platformReceivable', '100');
          this.$set(this.dataModule, 'merchantReceivable', '0');
        }
      } else if (!this.typeRadioDataType) {
        // 通用规则
        if (val == '1') {
          /** 清分 */
          this.closeTypeDataType = true;
          this.lineCloseTypeDataType = false;
          this.dataModule.clearingRule = '1';
          this.dataModule.platformReceivable = '';
          this.dataModule.merchantReceivable = '';
          this.resetLineReceivable();
          this.$set(this.dataModule, 'lineClearingRule', '');
        } else if (val == '2') {
          /** 结算 */
          this.closeTypeDataType = false;
          this.lineCloseTypeDataType = false;
          this.dataModule.clearingRule = '1';
          this.resetLineReceivable();
          this.$set(this.dataModule, 'lineClearingRule', '');
          this.$set(this.dataModule, 'platformReceivable', '100');
          this.$set(this.dataModule, 'merchantReceivable', '0');
        } else if (val == '3') {
          /** 平台 */
          this.closeTypeDataType = false;
          this.lineCloseTypeDataType = true;
          this.resetReceivable();
          this.$set(this.dataModule, 'clearingRule', '1');
          this.$set(this.dataModule, 'lineClearingRule', '1');
          this.$set(this.dataModule, 'platformReceivable', '100');
          this.$set(this.dataModule, 'merchantReceivable', '0');
        }
      }
    },
    // 规则类型
    handleTypeGadio(val) {
      if (val == '1') {
        this.typeRadioDataType = true;
      } else if (val == '2') {
        this.typeRadioDataType = false;
      }
      this.dataModule = {};
      this.closeTypeDataType = true;
      this.resetFormRule();
      this.resetReceivable();
      this.resetLineReceivable();
      /** 重置默认表单线下 */
      this.resetDate();
      this.$set(this.dataModule, 'ruleType', val);
      /** 规则类型 */
      this.$set(this.dataModule, 'settlementType', '1');
      /** 结算类型 */
      this.$set(this.dataModule, 'clearingRule', '1');
      /** 清分规则默认选中 */
      this.$set(this.dataModule, 'clearingCycleMode', '1'); /** 清分周期类型默认选中 */
    },

    handleSubmitCancel(formName) {
      this.isShow = false;
    },

    handleSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {

          this.$store.dispatch(`${namespace}/getSettlementByCodeLevel`, this.dataModule).then(res => {
            if (res.data.ret === 0) {
              let data = res.data.data;
              if (data > 0) {

                Modal.confirm({
                  render: (h, params) => {
                    return h("div", [
                      h(
                          "div",
                          {
                            class: "selfConfirmRule"
                          },
                          "该规则与另一条清分规则的生效时间和优先级有重复，提交后另一条清分规则将自动作废，是否确认提交?"
                      )
                    ]);
                  },
                  onOk: () => {
                    return this.$store.dispatch(`${namespace}/save`, this.dataModule).then(res => {
                      if (res.ret === 0) {
                        this.$Message.success(res.msg);
                        this.isShow = false;
                        this.$store.dispatch(`${namespace}/query`);
                      }
                    });
                  }
                })
              } else {
                this.$store.dispatch(`${namespace}/save`, this.dataModule).then(e => {
                  if (e.ret === 0) {
                    this.$Message.success({
                      content: e.msg
                    });
                    this.isShow = false;
                    this.reload(); // 重新刷新页面
                    // this.$store.dispatch(`${namespace}/query`);
                  }
                });
              }
            }
          })

        } else {
          return false;
        }
      });
    },

    handleAdd() {
      this.dataModule = {}
      this.isShow = true;
      this.resetFormAll();
      this.title = "新增清分规则";
      this.dataModule.ruleType = '1';
      /** 规则类型默认选中 */
      // this.dataModule.settlementType = '1'; /** 结算类型默认选中 */
      this.$set(this.dataModule, 'settlementType', '1')
      this.$set(this.dataModule, 'clearingCycleMode', '1');
      /** 清分周期类型默认选中 */
      this.$set(this.dataModule, 'clearingRule', '1');
      /** 清分规则默认选中 */
      this.getMerchant();
    },

    handleSearch() {
      let page = {
        currentPage: 1,
        pageSize: 10
      }
      
      this.$store.dispatch(`${namespace}/query`, {...this.searchModule, ...page});
    },

    onSortChange(sort) {
      if (sort.order === "normal") {
        this.queryParam.order = [];
      } else {
        this.queryParam.order = [sort.key + " " + sort.order];
      }
      this.handleSearch();
    },

    /** 表单重置 */
    resetFormAll() {
      this.$refs['dataModule'].resetFields()
    },

    /** 重置商户 - 时间 */
    resetDate() {
      this.$refs['dataModule'].fields.forEach(function (e) {
        if (e.prop == 'merchantCode' || e.prop == 'validTime') e.resetField();
      })
    },

    /** 表单通用规则重置 */
    resetFormRule() {
      this.$refs['dataModule'].fields.forEach(function (e) {
        if (e.prop == 'ruleName' || e.prop == 'clearingCycleValue' || e.prop == 'priorityLevel') e.resetField();
      })
    },

    /** 取消平台应收与商户应收验证 */
    resetReceivable() {
      this.$refs['dataModule'].fields.forEach(function (e) {
        if (e.prop == 'platformReceivable' || e.prop == 'merchantReceivable') e.resetField();
      })
    },

    /** 取消线下平台应收与商户应收验证 */
    resetLineReceivable() {
      this.$refs['dataModule'].fields.forEach(function (e) {
        if (e.prop == 'linePlatformReceivable' || e.prop == 'lineMerchantReceivable') e.resetField();
      })
    }
  },
  mounted() {
    this.$bus.$on("actionType", data => {
      let id = data.id
      if (data.type === "edit") {
        this.isShowDetele = true;
        this.$store.dispatch(`${namespace}/getDetail`, id).then(res => {
          if (res) {
            this.dataModuleDetele = res.data;
          }

        });
      } else if (data.type === "delete") {
        Modal.confirm({
          render: (h, params) => {
            return h("div", [
              h('div', {
                style: "margin-bottom:10px;vertical-align: middle;font-size: 16px;color: #17233d;font-weight: 700; border-bottom: 1px solid #ddd"
              }, '提示'),
              h("div", {
                    class: "selfConfirm"
                  },
                  "作废后不可再次生效，是否确认作废?"
              )
            ]);
          },
          // title: '提示',
          // content: '作废后不可再次生效，是否确认作废?',
          // okText: '确定',
          // cancelText: '取消',
          onOk: () => {
            return this.$store.dispatch(`${namespace}/delete`, id).then(e => {
              if (e.ret === 0) {
                this.$Message.success(e.msg);
                // this.$store.dispatch(`${namespace}/query`);
                this.reload(); // 重新刷新页面
              } else {
                this.$Message.warning(e.msg);
              }
            });
          }
        });
      }
    });
  },
  beforeDestroy() {
    this.$bus.$off("actionType");
  },
};
</script>

<style lang="less" scoped>
.rule {
  .ruleModal {
    height: 100px;
  }

  .searchDate {
    width: 100% !important;
  }

}

.offlineSettleRule {
  background-color: #f2f2f2;
  margin-bottom: 10px;
}

.ruleDeteleModal .ruleDeteleTitle {
  padding-bottom: 6px;
  margin-bottom: 10px;
  border-bottom: 1px solid #999;
}

.ruleDeteleModal .ivu-form-item {
  margin-bottom: 0px;
}

.controlNo {
  margin-bottom: 10px;
}
</style>
